<template>
  <div>
    <div style="margin-bottom: 16px;">
      <a-button type="primary" @click="showQuestionModal">
        <a-icon type="plus" /> 添加题目
      </a-button>
      <a-divider type="vertical" />
      <a-button @click="importQuestions">
        <a-icon type="upload" /> 导入题目
      </a-button>
      <a-divider type="vertical" />
      <a-button @click="exportQuestions">
        <a-icon type="download" /> 导出题目
      </a-button>
    </div>
    
    <a-table
      :columns="columns"
      :dataSource="data"
      rowKey="id"
      :pagination="false"
    >
      <template slot="type" slot-scope="text">
        <a-tag :color="getTypeColor(text)">{{text}}</a-tag>
      </template>
      <template slot="required" slot-scope="text">
        <a-tag :color="text ? 'red' : 'default'">{{text ? '必答' : '选答'}}</a-tag>
      </template>
      <template slot="action" slot-scope="text, record">
        <a-button type="link" size="small" @click="editQuestion(record)">编辑</a-button>
        <a-divider type="vertical" />
        <a-button type="link" size="small" @click="deleteQuestion(record)">删除</a-button>
<!--        <a-divider type="vertical" />
        <a-button type="link" size="small" @click="moveUp(record)">上移</a-button>
        <a-divider type="vertical" />
        <a-button type="link" size="small" @click="moveDown(record)">下移</a-button> -->
      </template>
    </a-table>
    
    <a-modal
      :title="questionModalTitle"
      :visible="questionModalVisible"
      @ok="handleQuestionOk"
      @cancel="handleQuestionCancel"
      :width="700"
    >
      <a-form :form="questionForm" layout="vertical">
        <a-form-item label="题目类型">
          <a-radio-group
            v-decorator="['type', { initialValue: 'single', rules: [{ required: true }] }]"
            @change="handleTypeChange"
          >
            <a-radio value="single">单选题</a-radio>
            <a-radio value="multiple">多选题</a-radio>
            <a-radio value="text">文本题</a-radio>
            <a-radio value="score">评分题</a-radio>
          </a-radio-group>
        </a-form-item>
        
        <a-form-item label="题目内容">
          <a-input
            v-decorator="['content', { rules: [{ required: true, message: '请输入题目内容' }] }]"
            placeholder="请输入题目内容"
          />
        </a-form-item>
        
        <a-form-item label="是否必答">
          <a-switch
            v-decorator="['required', { valuePropName: 'checked', initialValue: true }]"
            checked-children="必答"
            un-checked-children="选答"
          />
        </a-form-item>
        
        <template v-if="questionForm.getFieldValue('type') !== 'text'">
          <a-form-item label="选项设置">
            <a-button type="dashed" @click="addOption" style="width: 100%">
              <a-icon type="plus" /> 添加选项
            </a-button>
          </a-form-item>
          
          <a-form-item v-if="questionForm.getFieldValue('type') === 'score'">
            <a-alert message="评分题需要设置5个选项，分别对应1-5分的评分标准" type="info" show-icon />
          </a-form-item>
          
          <div v-for="(option, index) in options" :key="index" style="margin-bottom: 8px;">
            <a-input
              v-model="option.text"
              placeholder="请输入选项内容"
              style="width: 80%; margin-right: 8px;"
            />
            <a-input-number
              v-if="questionForm.getFieldValue('type') === 'score'"
              v-model="option.score"
              :min="1"
              :max="5"
              placeholder="分值"
              style="width: 18%"
            />
            <a-button @click="removeOption(index)" type="danger" icon="delete" />
          </div>
        </template>
      </a-form>
    </a-modal>
    
    <a-modal
      title="导入题目"
      :visible="importModalVisible"
      @ok="handleImportOk"
      @cancel="handleImportCancel"
    >
      <a-upload-dragger
        name="file"
        :multiple="false"
        :action="uploadUrl"
        @change="handleImportChange"
      >
        <p class="ant-upload-drag-icon">
          <a-icon type="inbox" />
        </p>
        <p class="ant-upload-text">点击或拖拽文件到此处上传</p>
        <p class="ant-upload-hint">支持Excel文件导入，请按照模板格式填写</p>
      </a-upload-dragger>
      <div style="margin-top: 16px;">
        <a-button type="link" @click="downloadTemplate">下载导入模板</a-button>
      </div>
    </a-modal>
  </div>
</template>

<script>
export default {
  props: {
    type: {
      type: String,
      required: true,
      validator: value => ['student', 'supervisor', 'leader'].includes(value)
    }
  },
  data() {
    return {
      columns: [
        {
          title: '序号',
          dataIndex: 'index',
          key: 'index',
          width: 60
        },
        {
          title: '题目类型',
          dataIndex: 'type',
          key: 'type',
          scopedSlots: { customRender: 'type' },
          width: 120
        },
        {
          title: '题目内容',
          dataIndex: 'content',
          key: 'content'
        },
        {
          title: '必答',
          dataIndex: 'required',
          key: 'required',
          scopedSlots: { customRender: 'required' },
          width: 80
        },
        {
          title: '操作',
          key: 'action',
          scopedSlots: { customRender: 'action' },
          width: 220
        }
      ],
      data: this.getSampleQuestions(),
      questionModalVisible: false,
      importModalVisible: false,
      questionModalTitle: '添加题目',
      currentQuestion: null,
      options: [],
      uploadUrl: 'https://www.mocky.io/v2/5cc8019d300000980a055e76' // 模拟上传地址
    }
  },
  beforeCreate() {
    this.questionForm = this.$form.createForm(this, { name: 'question_form' })
  },
  methods: {
    getSampleQuestions() {
      const questions = {
        student: [
          {
            id: 's1',
            index: 1,
            type: '评分题',
            content: '教师的教学态度认真负责',
            required: true,
            options: [
              { text: '非常满意', score: 5 },
              { text: '满意', score: 4 },
              { text: '一般', score: 3 },
              { text: '不满意', score: 2 },
              { text: '非常不满意', score: 1 }
            ]
          },
          {
            id: 's2',
            index: 2,
            type: '评分题',
            content: '教师的教学内容充实，重点突出',
            required: true,
            options: [
              { text: '非常满意', score: 5 },
              { text: '满意', score: 4 },
              { text: '一般', score: 3 },
              { text: '不满意', score: 2 },
              { text: '非常不满意', score: 1 }
            ]
          },
          {
            id: 's3',
            index: 3,
            type: '单选题',
            content: '教师的教学方法是否适合本课程',
            required: true,
            options: [
              { text: '非常适合' },
              { text: '适合' },
              { text: '一般' },
              { text: '不太适合' },
              { text: '不适合' }
            ]
          }
        ],
        supervisor: [
          {
            id: 'su1',
            index: 1,
            type: '评分题',
            content: '教师的教学准备是否充分',
            required: true,
            options: [
              { text: '非常充分', score: 5 },
              { text: '充分', score: 4 },
              { text: '一般', score: 3 },
              { text: '不充分', score: 2 },
              { text: '非常不充分', score: 1 }
            ]
          },
          {
            id: 'su2',
            index: 2,
            type: '评分题',
            content: '课堂组织是否有序',
            required: true,
            options: [
              { text: '非常好', score: 5 },
              { text: '好', score: 4 },
              { text: '一般', score: 3 },
              { text: '差', score: 2 },
              { text: '非常差', score: 1 }
            ]
          },
          {
            id: 'su3',
            index: 3,
            type: '文本题',
            content: '对本节课的改进建议',
            required: false
          }
        ],
        leader: [
          {
            id: 'l1',
            index: 1,
            type: '评分题',
            content: '教师的教学效果总体评价',
            required: true,
            options: [
              { text: '优秀', score: 5 },
              { text: '良好', score: 4 },
              { text: '中等', score: 3 },
              { text: '合格', score: 2 },
              { text: '不合格', score: 1 }
            ]
          },
          {
            id: 'l2',
            index: 2,
            type: '多选题',
            content: '教师的教学特色（可多选）',
            required: false,
            options: [
              { text: '教学内容新颖' },
              { text: '教学方法创新' },
              { text: '师生互动良好' },
              { text: '理论与实践结合' },
              { text: '其他' }
            ]
          }
        ]
      }
      return questions[this.type].map((q, i) => ({ ...q, index: i + 1 }))
    },
    getTypeColor(type) {
      const colors = {
        '单选题': 'blue',
        '多选题': 'geekblue',
        '文本题': 'orange',
        '评分题': 'green'
      }
      return colors[type] || 'default'
    },
    showQuestionModal() {
      this.currentQuestion = null
      this.questionModalTitle = '添加题目'
      this.questionModalVisible = true
      this.options = []
      this.$nextTick(() => {
        this.questionForm.resetFields()
      })
    },
    editQuestion(record) {
      this.currentQuestion = record
      this.questionModalTitle = '编辑题目'
      this.questionModalVisible = true
      this.options = [...(record.options || [])]
      this.$nextTick(() => {
        this.questionForm.setFieldsValue({
          type: this.getTypeValue(record.type),
          content: record.content,
          required: record.required
        })
      })
    },
    getTypeValue(type) {
      const map = {
        '单选题': 'single',
        '多选题': 'multiple',
        '文本题': 'text',
        '评分题': 'score'
      }
      return map[type] || 'single'
    },
    getTypeLabel(type) {
      const map = {
        'single': '单选题',
        'multiple': '多选题',
        'text': '文本题',
        'score': '评分题'
      }
      return map[type] || '单选题'
    },
    deleteQuestion(record) {
      this.$confirm({
        title: '确认删除',
        content: `确定要删除题目"${record.content}"吗？`,
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk: () => {
          this.data = this.data.filter(item => item.id !== record.id)
          // 重新排序
          this.data = this.data.map((item, index) => ({ ...item, index: index + 1 }))
          this.$message.success('删除成功')
        }
      })
    },
    moveUp(record) {
      const index = this.data.findIndex(item => item.id === record.id)
      if (index > 0) {
        const newData = [...this.data]
        const temp = newData[index - 1]
        newData[index - 1] = newData[index]
        newData[index] = temp
        this.data = newData.map((item, i) => ({ ...item, index: i + 1 }))
      }
    },
    moveDown(record) {
      const index = this.data.findIndex(item => item.id === record.id)
      if (index < this.data.length - 1) {
        const newData = [...this.data]
        const temp = newData[index + 1]
        newData[index + 1] = newData[index]
        newData[index] = temp
        this.data = newData.map((item, i) => ({ ...item, index: i + 1 }))
      }
    },
    addOption() {
      this.options.push({
        text: '',
        score: this.options.length + 1
      })
    },
    removeOption(index) {
      this.options.splice(index, 1)
    },
    handleTypeChange(e) {
      if (e.target.value === 'score') {
        // 如果是评分题，自动生成5个选项
        this.options = [
          { text: '非常满意', score: 5 },
          { text: '满意', score: 4 },
          { text: '一般', score: 3 },
          { text: '不满意', score: 2 },
          { text: '非常不满意', score: 1 }
        ]
      } else if (e.target.value !== 'text') {
        // 如果不是文本题，初始化2个选项
        this.options = [
          { text: '选项1' },
          { text: '选项2' }
        ]
      } else {
        this.options = []
      }
    },
    handleQuestionOk() {
      this.questionForm.validateFields((err, values) => {
        if (!err) {
          const question = {
            type: this.getTypeLabel(values.type),
            content: values.content,
            required: values.required,
            options: [...this.options]
          }
          
          if (this.currentQuestion) {
            // 更新
            Object.assign(this.currentQuestion, question)
            this.$message.success('更新成功')
          } else {
            // 新增
            const newQuestion = {
              id: `${this.type}_${Date.now()}`,
              index: this.data.length + 1,
              ...question
            }
            this.data.push(newQuestion)
            this.$message.success('添加成功')
          }
          this.questionModalVisible = false
        }
      })
    },
    handleQuestionCancel() {
      this.questionModalVisible = false
    },
    importQuestions() {
      this.importModalVisible = true
    },
    exportQuestions() {
      this.$message.info('导出功能将在实际应用中实现')
    },
    downloadTemplate() {
      this.$message.info('模板下载功能将在实际应用中实现')
    },
    handleImportChange(info) {
      if (info.file.status === 'done') {
        this.$message.success(`${info.file.name} 文件上传成功`)
        this.importModalVisible = false
        // 这里应该处理导入的数据
      } else if (info.file.status === 'error') {
        this.$message.error(`${info.file.name} 文件上传失败`)
      }
    },
    handleImportOk() {
      this.importModalVisible = false
    },
    handleImportCancel() {
      this.importModalVisible = false
    }
  }
}
</script>